package server;

import static org.junit.Assert.*;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class ConnectionMapTest
{
	private static ConnectionMap map;
	private static Connection testConnection;
	private static Server server;
	
	@BeforeClass
	public static void beforeTests() throws InstantiationException
	{
		server = new Server("config.xml");
		
		Thread thread = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				server.run();
			}
		});
		
		thread.start();
		
		while (!server.isReady())
		{
			try
			{
				Thread.sleep(10);
			}
			catch (InterruptedException e) {}
		}
	}
	@AfterClass
	public static void afterTests()
	{
		server.stop();
		
		while (server.isRunning())
		{
			try
			{
				Thread.sleep(10);
			}
			catch (InterruptedException e) {}
		}
	}
	@Before
	public void setUpMap() throws UnknownHostException, IOException, InstantiationException
	{
		map = new ConnectionMap();
		
		testConnection = new Connection(0, getSocket());
		
		map.put(0, testConnection);
	}
	@After
	public void destroyMap()
	{
		map = null;
	}
	public Socket getSocket() throws UnknownHostException, IOException
	{
		return new Socket("127.0.0.1", 62455);
	}
	@Test
	public void testSize() throws UnknownHostException, InstantiationException, IOException
	{
		assertEquals(1, map.size());
		
		map.clear();
		
		assertEquals(0, map.size());
		
		map.put(0, new Connection(0, new Socket("127.0.0.1", 62455)));
		
		assertEquals(1, map.size());
		
		map.put(1, new Connection(1, new Socket("127.0.0.1", 62455)));
		
		assertEquals(2, map.size());
	}

	@Test
	public void testIsEmpty()
	{
		assertFalse(map.isEmpty());
		
		map.clear();
		
		assertTrue(map.isEmpty());
	}

	@Test
	public void testClear()
	{
		map.clear();
		
		assertTrue(map.isEmpty());
	}

	@Test
	public void testRemove()
	{
		map.remove(0);
		
		assertFalse(map.containsKey(0));
	}

	@Test
	public void testContainsKey()
	{
		assertTrue(map.containsKey(0));
		
		map.clear();
		
		assertFalse(map.containsKey(0));
	}

	@Test
	public void testContainsValue()
	{
		assertTrue(map.containsValue(testConnection));
		
		map.clear();
		
		assertFalse(map.containsValue(testConnection));
	}

	@Test
	public void testGet()
	{
		assertEquals(testConnection, map.get(0));
		
		map.clear();
		
		assertNull(map.get(0));
	}

	@Test
	public void testPutServerConnection() throws UnknownHostException, InstantiationException, IOException
	{
		map.putServerConnection(1, new Connection(1, getSocket()));
		
		assertEquals(2, map.size());
		assertEquals(1, map.serverConnectionValues().size());
	}

}
